package com.dmbjz.moddymq.service;


import com.dmbjz.moddymq.dao.TransMessageDao;
import com.dmbjz.moddymq.enummeration.TransMessageType;
import com.dmbjz.moddymq.po.TransMessagePO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;


/* 不可路由消息处理Service */
@Service
public class TransMessageServiceImpl implements TransMessageService {

    @Autowired
    TransMessageDao transMessageDao;

    private static final String serviceName = "orderService";


    @Override
    public TransMessagePO messageSendReady(String id,String exchange, String routingKey, String body) {
        TransMessagePO transMessagePO = new TransMessagePO();
        transMessagePO.setId(id);
        transMessagePO.setService(serviceName);
        transMessagePO.setExchange(exchange);
        transMessagePO.setRoutingKey(routingKey);
        transMessagePO.setPayload(body);
        transMessagePO.setDate(LocalDateTime.now());
        transMessagePO.setSequence(0);
        transMessagePO.setType(TransMessageType.SEND);
        transMessageDao.insert(transMessagePO);
        return transMessagePO;
    }

    @Override
    public void messageSendSuccess(String id) {
        transMessageDao.delete(id, serviceName);
    }


    @Override
    public TransMessagePO messageSendReturn(String id, String exchange, String routingKey, String body) {
        return messageSendReady(id,exchange, routingKey, body);
    }


    @Override
    public List<TransMessagePO> listReadyMessages() {
        return transMessageDao.selectByTypeAndService(TransMessageType.SEND.toString() ,serviceName);
    }


    /* 在修改不可路由消息状态时需要使用分布式锁进行保障，保证同一时间只有一个任务可以进行状态，这里进行省略  */
    @Override
    public void messageResend(String id) {
        TransMessagePO transMessagePO = transMessageDao.selectByIdAndService(id, serviceName);
        transMessagePO.setSequence(transMessagePO.getSequence() + 1);
        transMessageDao.update(transMessagePO);
    }


    /* 在修改不可路由消息状态时需要使用分布式锁进行保障，保证同一时间只有一个任务可以进行状态，这里进行省略 */
    @Override
    public void messageDead(String id) {
        TransMessagePO transMessagePO = transMessageDao.selectByIdAndService(id, serviceName);
        transMessagePO.setType(TransMessageType.DEAD);
        transMessageDao.update(transMessagePO);
    }

}
